﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace SystemCenterSoa.BaseLibrary.Tools.losTools
{
    public class DiTools
    {
        public static IServiceProvider Instance { get; set; }

        /// <summary>
        /// 获取依赖注入对象, 注意只能获取AddTransient和AddSingleton这两种类型的注入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetDiObj<T>()
        {
            return Instance.GetService<T>();
        }
        /// <summary>
        /// 用于获取Scoped类型的注入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetDiObjScoped<T>()
        {
            IHttpContextAccessor httpContextAccessor = Instance.GetService<IHttpContextAccessor>();
            if (httpContextAccessor.HttpContext != null)
                return httpContextAccessor.HttpContext.RequestServices.GetService<T>();

            return default(T);
        }
    }
}
